{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Concise reference\n",
    "\n",
    "> An information-dense guide showing LLMs how to create FastHTML apps with MonsterUI and Fastlite\n",
    "\n",
    "- order: 3"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## About FastHTML"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from fasthtml.common import *"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "FastHTML is a python library which brings together Starlette, Uvicorn, HTMX, and fastcore's `FT` \"FastTags\" into a library for creating server-rendered hypermedia applications. The `FastHTML` class itself inherits from `Starlette`, and adds decorator-based routing with many additions, Beforeware, automatic `FT` to HTML rendering, and much more.\n",
    "\n",
    "Things to remember when writing FastHTML apps:\n",
    "\n",
    "- *Not* compatible with FastAPI syntax; FastHTML is for HTML-first apps, not API services (although it can implement APIs too)\n",
    "- FastHTML includes support for Pico CSS and the fastlite sqlite library, although using both are optional; sqlalchemy can be used directly or via the fastsql library, and any CSS framework can be used. MonsterUI is a richer FastHTML-first component framework with similar capabilities to shadcn\n",
    "- FastHTML is compatible with JS-native web components and any vanilla JS library, but not with React, Vue, or Svelte\n",
    "- Use `serve()` for running uvicorn (`if __name__ == \"__main__\"` is not needed since it's automatic)\n",
    "- When a title is needed with a response, use `Titled`; note that that already wraps children in `Container`, and already includes both the meta title as well as the H1 element."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Minimal App"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The code examples here use fast.ai style: prefer ternary op, 1-line docstring, minimize vertical space, etc. (Normally fast.ai style uses few if any comments, but they're added here as documentation.)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A minimal FastHTML app looks something like this:\n",
    "\n",
    "```python\n",
    "# Meta-package with all key symbols from FastHTML and Starlette. Import it like this at the start of every FastHTML app.\n",
    "from fasthtml.common import *\n",
    "# The FastHTML app object and shortcut to `app.route`\n",
    "app,rt = fast_app()\n",
    "\n",
    "# Enums constrain the values accepted for a route parameter\n",
    "name = str_enum('names', 'Alice', 'Bev', 'Charlie')\n",
    "\n",
    "# Passing a path to `rt` is optional. If not passed (recommended), the function name is the route ('/foo')\n",
    "# Both GET and POST HTTP methods are handled by default\n",
    "# Type-annotated params are passed as query params (recommended) unless a path param is defined (which it isn't here)\n",
    "@rt\n",
    "def foo(nm: name):\n",
    "    # `Title` and `P` here are FastTags: direct m-expression mappings of HTML tags to Python functions with positional and named parameters. All standard HTML tags are included in the common wildcard import.\n",
    "    # When a tuple is returned, this returns concatenated HTML partials. HTMX by default will use a title HTML partial to set the current page name. HEAD tags (e.g. Meta, Link, etc) in the returned tuple are automatically placed in HEAD; everything else is placed in BODY.\n",
    "    # FastHTML will automatically return a complete HTML document with appropriate headers if a normal HTTP request is received. For an HTMX request, however, just the partials are returned.\n",
    "    return Title(\"FastHTML\"), H1(\"My web app\"), P(f\"Hello, {name}!\")\n",
    "# By default `serve` runs uvicorn on port 5001. Never write `if __name__ == \"__main__\"` since `serve` checks it internally.\n",
    "serve()\n",
    "```\n",
    "\n",
    "To run this web app:\n",
    "\n",
    "```bash\n",
    "python main.py  # access via localhost:5001\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## FastTags (aka FT Components or FTs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "FTs are m-expressions plus simple sugar. Positional params map to children. Named parameters map to attributes. Aliases must be used for Python reserved words."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(title(('FastHTML',),{}),\n",
       " h1(('My web app',),{}),\n",
       " p((\"Let's do this!\",),{'class': 'myclass'}))"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tags = Title(\"FastHTML\"), H1(\"My web app\"), P(f\"Let's do this!\", cls=\"myclass\")\n",
    "tags"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This example shows key aspects of how FTs handle attributes:\n",
    "\n",
    "```python\n",
    "Label(\n",
    "    \"Choose an option\", \n",
    "    Select(\n",
    "        Option(\"one\", value=\"1\", selected=True),  # True renders just the attribute name\n",
    "        Option(\"two\", value=2, selected=False),   # Non-string values are converted to strings. False omits the attribute entirely\n",
    "        cls=\"selector\", id=\"counter\",             # 'cls' becomes 'class'\n",
    "        **{'@click':\"alert('Clicked');\"},         # Dict unpacking for attributes with special chars\n",
    "    ),\n",
    "    _for=\"counter\",                               # '_for' becomes 'for' (can also use 'fr')\n",
    ")\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Classes with `__ft__` defined are rendered using that method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'<p>test</p>\\n'"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class FtTest:\n",
    "    def __ft__(self): return P('test')\n",
    "    \n",
    "to_xml(FtTest())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can create new FTs by importing the new component from `fasthtml.components`. If the FT doesn't exist within that module, FastHTML will create it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "```html\n",
       "<some-never-before-used-tag></some-never-before-used-tag>\n",
       "```"
      ],
      "text/plain": [
       "some-never-before-used-tag((),{})"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from fasthtml.components import Some_never_before_used_tag\n",
    "\n",
    "Some_never_before_used_tag()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "FTs can be combined by defining them as a function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'<div class=\"hero\">\\n  <h1>Hello World</h1>\\n  <p>This is a hero statement</p>\\n</div>\\n'"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def Hero(title, statement): return Div(H1(title),P(statement), cls=\"hero\")\n",
    "to_xml(Hero(\"Hello World\", \"This is a hero statement\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When handling a response,  FastHTML will automatically render FTs using the `to_xml` function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'<title>FastHTML</title>\\n<h1>My web app</h1>\\n<p class=\"myclass\">Let&#x27;s do this!</p>\\n'"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "to_xml(tags)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## JS"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `Script` function allows you to include JavaScript. You can use Python to generate parts of your JS or JSON like this:\n",
    "\n",
    "```python\n",
    "# In future snippets this import will not be shown, but is required\n",
    "from fasthtml.common import * \n",
    "app,rt = fast_app(hdrs=[Script(src=\"https://cdn.plot.ly/plotly-2.32.0.min.js\")])\n",
    "# `index` is a special function name which maps to the `/` route. \n",
    "@rt\n",
    "def index():\n",
    "    data = {'somedata':'fill me in…'}\n",
    "    # `Titled` returns a title tag and an h1 tag with the 1st param, with remaining params as children in a `Main` parent.\n",
    "    return Titled(\"Chart Demo\", Div(id=\"myDiv\"), Script(f\"var data = {data}; Plotly.newPlot('myDiv', data);\"))\n",
    "# In future snippets `serve() will not be shown, but is required\n",
    "serve()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Prefer Python whenever possible over JS. Never use React or shadcn."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## fast_app hdrs"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```python\n",
    "# In future snippets we'll skip showing the `fast_app` call if it has no params\n",
    "app, rt = fast_app(\n",
    "    pico=False, # The Pico CSS framework is included by default, so pass `False` to disable it if needed. No other CSS frameworks are included.\n",
    "    # These are added to the `head` part of the page for non-HTMX requests.\n",
    "    hdrs=(\n",
    "        Link(rel='stylesheet', href='assets/normalize.min.css', type='text/css'),\n",
    "        Link(rel='stylesheet', href='assets/sakura.css', type='text/css'),\n",
    "        Style(\"p {color: red;}\"),\n",
    "        # `MarkdownJS` and `HighlightJS` are available via concise functions\n",
    "        MarkdownJS(), HighlightJS(langs=['python', 'javascript', 'html', 'css']),\n",
    "        # by default, all standard static extensions are served statically from the web app dir,\n",
    "        #   which can be modified using e.g `static_path='public'`\n",
    "        )\n",
    ")\n",
    "\n",
    "@rt\n",
    "def index(req): return Titled(\"Markdown rendering example\",\n",
    "                              # This will be client-side rendered to HTML with highlight-js\n",
    "                              Div(\"*hi* there\",cls=\"marked\"),\n",
    "                              # This will be syntax highlighted\n",
    "                              Pre(Code(\"def foo(): pass\")))\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Responses"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Routes can return various types:\n",
    "\n",
    "1. FastTags or tuples of FastTags (automatically rendered to HTML)\n",
    "2. Standard Starlette responses (used directly)\n",
    "3. JSON-serializable types (returned as JSON in a plain text response)\n",
    "\n",
    "```python\n",
    "@rt(\"/{fname:path}.{ext:static}\")\n",
    "async def serve_static_file(fname:str, ext:str): return FileResponse(f'public/{fname}.{ext}')\n",
    "\n",
    "app, rt = fast_app(hdrs=(MarkdownJS(), HighlightJS(langs=['python', 'javascript'])))\n",
    "@rt\n",
    "def index(): \n",
    "    return Titled(\"Example\",\n",
    "                  Div(\"*markdown* here\", cls=\"marked\"),\n",
    "                  Pre(Code(\"def foo(): pass\")))\n",
    "```\n",
    "\n",
    "Route functions can be used in attributes like `href` or `action` and will be converted to paths. Use `.to()` to generate paths with query parameters.\n",
    "\n",
    "```python\n",
    "@rt\n",
    "def profile(email:str): return fill_form(profile_form, profiles[email])\n",
    "\n",
    "profile_form = Form(action=profile)(\n",
    "    Label(\"Email\", Input(name=\"email\")),\n",
    "    Button(\"Save\", type=\"submit\")\n",
    ")\n",
    "\n",
    "user_profile_path = profile.to(email=\"user@example.com\")  # '/profile?email=user%40example.com'\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from dataclasses import dataclass\n",
    "\n",
    "app,rt = fast_app()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When a route handler function is used as a fasttag attribute (such as `href`, `hx_get`, or `action`) it is converted to that route's path. `fill_form` is used to copy an object's matching attrs into matching-name form fields."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@dataclass\n",
    "class Profile: email:str; phone:str; age:int\n",
    "email = 'john@example.com'\n",
    "profiles = {email: Profile(email=email, phone='123456789', age=5)}\n",
    "@rt\n",
    "def profile(email:str): return fill_form(profile_form, profiles[email])\n",
    "\n",
    "profile_form = Form(method=\"post\", action=profile)(\n",
    "        Fieldset(\n",
    "            Label('Email', Input(name=\"email\")),\n",
    "            Label(\"Phone\", Input(name=\"phone\")),\n",
    "            Label(\"Age\", Input(name=\"age\"))),\n",
    "        Button(\"Save\", type=\"submit\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Testing"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can use `TestClient` for testing."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from starlette.testclient import TestClient"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<form enctype=\"multipart/form-data\" method=\"post\" action=\"/profile\"><fieldset><label>Email       <input name=\"email\" value=\"john@example.com\">\n",
      "</label><label>Phone       <input name=\"phone\" value=\"123456789\">\n",
      "</label><label>Age       <input name=\"age\" value=\"5\">\n",
      "</label></fieldset><button type=\"submit\">Save</button></form>\n"
     ]
    }
   ],
   "source": [
    "path = \"/profile?email=john@example.com\"\n",
    "client = TestClient(app)\n",
    "htmx_req = {'HX-Request':'1'}\n",
    "print(client.get(path, headers=htmx_req).text)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Form Handling and Data Binding"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When a dataclass, namedtuple, etc. is used as a type annotation, the form body will be unpacked into matching attribute names automatically. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<form enctype=\"multipart/form-data\" method=\"post\" action=\"/profile\"><fieldset><label>Email       <input name=\"email\" value=\"john@example.com\">\n",
      "</label><label>Phone       <input name=\"phone\" value=\"7654321\">\n",
      "</label><label>Age       <input name=\"age\" value=\"25\">\n",
      "</label></fieldset><button type=\"submit\">Save</button></form>\n"
     ]
    }
   ],
   "source": [
    "@rt\n",
    "def edit_profile(profile: Profile):\n",
    "    profiles[email]=profile\n",
    "    return RedirectResponse(url=path)\n",
    "\n",
    "new_data = dict(email='john@example.com', phone='7654321', age=25)\n",
    "print(client.post(\"/edit_profile\", data=new_data, headers=htmx_req).text)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## fasttag Rendering Rules"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The general rules for rendering children inside tuples or fasttag children are: \n",
    "- `__ft__` method will be called (for default components like `P`, `H2`, etc. or if you define your own components)\n",
    "- If you pass a string, it will be escaped\n",
    "- On other python objects, `str()` will be called\n",
    "\n",
    "If you want to include plain HTML tags directly into e.g. a `Div()` they will get escaped by default (as a security measure to avoid code injections). This can be avoided by using `Safe(...)`, e.g to show a data frame use `Div(NotStr(df.to_html()))`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exceptions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "FastHTML allows customization of exception handlers.\n",
    "\n",
    "```python\n",
    "def not_found(req, exc): return Titled(\"404: I don't exist!\")\n",
    "exception_handlers = {404: not_found}\n",
    "app, rt = fast_app(exception_handlers=exception_handlers)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Cookies"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can set cookies using the `cookie()` function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " <p>Set</p>\n",
      "\n"
     ]
    }
   ],
   "source": [
    "@rt\n",
    "def setcook(): return P(f'Set'), cookie('mycookie', 'foobar')\n",
    "print(client.get('/setcook', headers=htmx_req).text)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Got foobar\n"
     ]
    }
   ],
   "source": [
    "@rt\n",
    "def getcook(mycookie:str): return f'Got {mycookie}'\n",
    "# If handlers return text instead of FTs, then a plaintext response is automatically created\n",
    "print(client.get('/getcook').text)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "FastHTML provide access to Starlette's request object automatically using special `request` parameter name (or any prefix of that name)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@rt\n",
    "def headers(req): return req.headers['host']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Request and Session Objects"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "FastHTML provides access to Starlette's session middleware automatically using the special `session` parameter name (or any prefix of that name)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@rt\n",
    "def profile(req, sess, user_id: int=None):\n",
    "    ip = req.client.host\n",
    "    sess['last_visit'] = datetime.now().isoformat()\n",
    "    visits = sess.setdefault('visit_count', 0) + 1\n",
    "    sess['visit_count'] = visits\n",
    "    user = get_user(user_id or sess.get('user_id'))\n",
    "    return Titled(f\"Profile: {user.name}\", \n",
    "                  P(f\"Visits: {visits}\"), \n",
    "                  P(f\"IP: {ip}\"),\n",
    "                  Button(\"Logout\", hx_post=logout))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Handler functions can return the `HtmxResponseHeaders` object to set HTMX-specific response headers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@rt\n",
    "def htmlredirect(app): return HtmxResponseHeaders(location=\"http://example.org\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## APIRouter"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`APIRouter` lets you organize routes across multiple files in a FastHTML app."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```python\n",
    "# products.py\n",
    "ar = APIRouter()\n",
    "\n",
    "@ar\n",
    "def details(pid: int): return f\"Here are the product details for ID: {pid}\"\n",
    "\n",
    "@ar\n",
    "def all_products(req):\n",
    "    return Div(\n",
    "        Div(\n",
    "            Button(\"Details\",hx_get=details.to(pid=42),hx_target=\"#products_list\",hx_swap=\"outerHTML\",),\n",
    "        ), id=\"products_list\")\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```python\n",
    "# main.py\n",
    "from products import ar,all_products\n",
    "\n",
    "app, rt = fast_app()\n",
    "ar.to_app(app)\n",
    "\n",
    "@rt\n",
    "def index():\n",
    "    return Div(\n",
    "        \"Products\",\n",
    "        hx_get=all_products, hx_swap=\"outerHTML\")\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Toasts"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Toasts can be of four types:\n",
    "\n",
    "- info\n",
    "- success\n",
    "- warning\n",
    "- error\n",
    "\n",
    "Toasts require the use of the `setup_toasts()` function, plus every handler needs:\n",
    "\n",
    "- The session argument\n",
    "- Must return FT components\n",
    "\n",
    "```python\n",
    "setup_toasts(app)\n",
    "\n",
    "@rt\n",
    "def toasting(session):\n",
    "    add_toast(session, f\"cooked\", \"info\")\n",
    "    add_toast(session, f\"ready\", \"success\")\n",
    "    return Titled(\"toaster\")\n",
    "```\n",
    "\n",
    "`setup_toasts(duration)` allows you to specify how long a toast will be visible before disappearing.10 seconds."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Authentication and authorization are handled with Beforeware, which functions that run before the route handler is called."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Auth"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def user_auth_before(req, sess):\n",
    "    # `auth` key in the request scope is automatically provided to any handler which requests it and can not be injected\n",
    "    auth = req.scope['auth'] = sess.get('auth', None)\n",
    "    if not auth: return RedirectResponse('/login', status_code=303)\n",
    "\n",
    "beforeware = Beforeware(\n",
    "    user_auth_before,\n",
    "    skip=[r'/favicon\\.ico', r'/static/.*', r'.*\\.css', r'.*\\.js', '/login', '/']\n",
    ")\n",
    "\n",
    "app, rt = fast_app(before=beforeware)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Server-Side Events (SSE)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "FastHTML supports the HTMX SSE extension."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "hdrs=(Script(src=\"https://unpkg.com/htmx-ext-sse@2.2.3/sse.js\"),)\n",
    "app,rt = fast_app(hdrs=hdrs)\n",
    "\n",
    "@rt\n",
    "def index(): return Div(hx_ext=\"sse\", sse_connect=\"/numstream\", hx_swap=\"beforeend show:bottom\", sse_swap=\"message\")\n",
    "\n",
    "# `signal_shutdown()` gets an event that is set on shutdown\n",
    "shutdown_event = signal_shutdown()\n",
    "\n",
    "async def number_generator():\n",
    "    while not shutdown_event.is_set():\n",
    "        data = Article(random.randint(1, 100))\n",
    "        yield sse_message(data)\n",
    "\n",
    "@rt\n",
    "async def numstream(): return EventStream(number_generator())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Websockets"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "FastHTML provides useful tools for HTMX's websockets extension."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# These HTMX extensions are available through `exts`:\n",
    "#   head-support preload class-tools loading-states multi-swap path-deps remove-me ws chunked-transfer\n",
    "app, rt = fast_app(exts='ws')\n",
    "\n",
    "def mk_inp(): return Input(id='msg', autofocus=True)\n",
    "\n",
    "@rt\n",
    "async def index(request):\n",
    "    # `ws_send` tells HTMX to send a message to the nearest websocket based on the trigger for the form element\n",
    "    cts = Div(\n",
    "        Div(id='notifications'),\n",
    "        Form(mk_inp(), id='form', ws_send=True),\n",
    "        hx_ext='ws', ws_connect='/ws')\n",
    "    return Titled('Websocket Test', cts)\n",
    "\n",
    "async def on_connect(send): await send(Div('Hello, you have connected', id=\"notifications\"))\n",
    "async def on_disconnect(ws): print('Disconnected!')\n",
    "\n",
    "@app.ws('/ws', conn=on_connect, disconn=on_disconnect)\n",
    "async def ws(msg:str, send):\n",
    "    # websocket hander returns/sends are treated as OOB swaps\n",
    "    await send(Div('Hello ' + msg, id=\"notifications\"))\n",
    "    return Div('Goodbye ' + msg, id=\"notifications\"), mk_inp()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Sample chatbot that uses FastHTML's `setup_ws` function:\n",
    "\n",
    "```py\n",
    "app = FastHTML(exts='ws')\n",
    "rt = app.route\n",
    "msgs = []\n",
    "\n",
    "@rt('/')\n",
    "def home():\n",
    "    return Div(hx_ext='ws', ws_connect='/ws')(\n",
    "        Div(Ul(*[Li(m) for m in msgs], id='msg-list')),\n",
    "        Form(Input(id='msg'), id='form', ws_send=True)\n",
    "    )\n",
    "\n",
    "async def ws(msg:str):\n",
    "    msgs.append(msg)\n",
    "    await send(Ul(*[Li(m) for m in msgs], id='msg-list'))\n",
    "\n",
    "send = setup_ws(app, ws)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Single File Uploads"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`Form` defaults to \"multipart/form-data\". A Starlette UploadFile is passed to the handler."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```python\n",
    "upload_dir = Path(\"filez\")\n",
    "\n",
    "@rt\n",
    "def index():\n",
    "    return (\n",
    "        Form(hx_post=upload, hx_target=\"#result\")(\n",
    "            Input(type=\"file\", name=\"file\"),\n",
    "            Button(\"Upload\", type=\"submit\")),\n",
    "        Div(id=\"result\")\n",
    "    )\n",
    "\n",
    "# Use `async` handlers where IO is used to avoid blocking other clients\n",
    "@rt\n",
    "async def upload(file: UploadFile):\n",
    "    filebuffer = await file.read()\n",
    "    (upload_dir / file.filename).write_bytes(filebuffer)\n",
    "    return P('Size: ', file.size)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For multi-file, use `Input(..., multiple=True)`, and a type annotation of `list[UploadFile]` in the handler. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Fastlite "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Fastlite and the MiniDataAPI specification it's built on are a CRUD-oriented API for working with SQLite. APSW and apswutils is used to connect to SQLite, optimized for speed and clean error handling."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from fastlite import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "db = database(':memory:') # or database('data/app.db')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Tables are normally constructed with classes, field types are specified as type hints. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Table user (id, name, active)>"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class Book: isbn: str; title: str; pages: int; userid: int\n",
    "# The transform arg instructs fastlite to change the db schema when fields change.\n",
    "# Create only creates a table if the table doesn't exist.\n",
    "books = db.create(Book, pk='isbn', transform=True)\n",
    "                \n",
    "class User: id: int; name: str; active: bool = True\n",
    "# If no pk is provided, id is used as the primary key.\n",
    "users = db.create(User, transform=True)\n",
    "users"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Fastlite CRUD operations"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every operation in fastlite returns a full superset of dataclass functionality. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "User(id=1, name='Alex', active=0)"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user = users.insert(name='Alex',active=False)\n",
    "user"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[User(id=1, name='Alex', active=0)]"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# List all records\n",
    "users()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "User(id=1, name='Alex', active=0)"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Limit, offset, and order results:\n",
    "users(order_by='name', limit=2, offset=1)\n",
    "\n",
    "# Filter on the results\n",
    "users(where=\"name='Alex'\")\n",
    "\n",
    "# Placeholder for avoiding injection attacks\n",
    "users(\"name=?\", ('Alex',))\n",
    "\n",
    "# A single record by pk\n",
    "users[user.id]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Test if a record exists by using `in` keyword on primary key:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "1 in users"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Updates (which take a dict or a typed object) return the updated record."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "User(id=1, name='Lauren', active=1)"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user.name='Lauren'\n",
    "user.active=True\n",
    "users.update(user)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`.xtra()` to automatically constrain queries, updates, and inserts from there on:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[User(id=1, name='Lauren', active=1)]"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "users.xtra(active=True)\n",
    "users()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Deleting by pk:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Table user (id, name, active)>"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "users.delete(user.id)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "NotFoundError is raised by pk `[]`, updates, and deletes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "User not found\n"
     ]
    }
   ],
   "source": [
    "try: users['Amy']\n",
    "except NotFoundError: print('User not found')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## MonsterUI"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "MonsterUI is a shadcn-like component library for FastHTML. It adds the Tailwind-based libraries FrankenUI and DaisyUI to FastHTML, as well as Python's mistletoe for Markdown, HighlightJS for code highlighting, and Katex for latex support, following semantic HTML patterns when possible. It is recommended for when you wish to go beyond the basics provided by FastHTML's built-in pico support.\n",
    "\n",
    "A minimal app:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from fasthtml.common import *\n",
    "from monsterui.all import *\n",
    "\n",
    "app, rt = fast_app(hdrs=Theme.blue.headers(highlightjs=True)) # Use MonsterUI blue theme and highlight code in markdown\n",
    "\n",
    "@rt\n",
    "def index():\n",
    "    socials = (('github','https://github.com/AnswerDotAI/MonsterUI'),)\n",
    "    return Titled(\"App\",\n",
    "        Card(\n",
    "            P(\"App\", cls=TextPresets.muted_sm),\n",
    "            # LabelInput, DivLAigned, and UkIconLink are non-semantic MonsterUI FT Components,\n",
    "            LabelInput('Email', type='email', required=True),\n",
    "            footer=DivLAligned(*[UkIconLink(icon,href=url) for icon,url in socials])))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "MonsterUI recommendations:\n",
    "\n",
    "- Use defaults as much as possible, for example `Container` in monsterui already has defaults for margins\n",
    "- Use `*T` for button styling consistency, for example `cls=ButtonT.destructive` for a red delete button or `cls=ButtonT.primary` for a CTA button\n",
    "- Use `Label*` functions for forms as much as possible (e.g. `LabelInput`, `LabelRange`) which creates and links both the `FormLabel` and user input appropriately to avoid boiler plate."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Flex Layout Elements (such as `DivLAligned` and `DivFullySpaced`) can be used to create layouts concisely"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def TeamCard(name, role, location=\"Remote\"):\n",
    "    icons = (\"mail\", \"linkedin\", \"github\")\n",
    "    return Card(\n",
    "        DivLAligned(\n",
    "            DiceBearAvatar(name, h=24, w=24),\n",
    "            Div(H3(name), P(role))),\n",
    "        footer=DivFullySpaced(\n",
    "            DivHStacked(UkIcon(\"map-pin\", height=16), P(location)),\n",
    "            DivHStacked(*(UkIconLink(icon, height=16) for icon in icons))))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Forms are styled and spaced for you without significant additional classes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def MonsterForm():\n",
    "    relationship = [\"Parent\",'Sibling', \"Friend\", \"Spouse\", \"Significant Other\", \"Relative\", \"Child\", \"Other\"]\n",
    "    return Div(\n",
    "        DivCentered(\n",
    "            H3(\"Emergency Contact Form\"),\n",
    "            P(\"Please fill out the form completely\", cls=TextPresets.muted_sm)),\n",
    "        Form(\n",
    "            Grid(LabelInput(\"Name\",id='name'),LabelInput(\"Email\",     id='email')),\n",
    "            H3(\"Relationship to patient\"),\n",
    "            Grid(*[LabelCheckboxX(o) for o in relationship], cols=4, cls='space-y-3'),\n",
    "            DivCentered(Button(\"Submit Form\", cls=ButtonT.primary))),\n",
    "        cls='space-y-4')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Text can be styled with markdown automatically with MonsterUI"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'<div><h1 class=\"uk-h1 text-4xl font-bold mt-12 mb-6\">My Document</h1>\\n<blockquote class=\"uk-blockquote pl-4 border-l-4 border-primary italic mb-6\">\\n<p class=\"text-lg leading-relaxed mb-6\">Important note here</p>\\n</blockquote>\\n<ul class=\"uk-list uk-list-bullet space-y-2 mb-6 ml-6 text-lg\">\\n<li class=\"leading-relaxed\">List item with <strong>bold</strong></li>\\n<li class=\"leading-relaxed\">Another with <code class=\"uk-codespan px-1\">code</code></li>\\n</ul>\\n<pre class=\"bg-base-200 rounded-lg p-4 mb-6\"><code class=\"language-python uk-codespan px-1 uk-codespan px-1 block overflow-x-auto\">def hello():\\n    print(\"world\")\\n</code></pre>\\n</div>'"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "render_md(\"\"\"\n",
    "# My Document\n",
    "\n",
    "> Important note here\n",
    "\n",
    "+ List item with **bold**\n",
    "+ Another with `code`\n",
    "\n",
    "```python\n",
    "def hello():\n",
    "    print(\"world\")\n",
    "```\n",
    "\"\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Or using semantic HTML:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def SemanticText():\n",
    "    return Card(\n",
    "        H1(\"MonsterUI's Semantic Text\"),\n",
    "        P(\n",
    "            Strong(\"MonsterUI\"), \" brings the power of semantic HTML to life with \",\n",
    "            Em(\"beautiful styling\"), \" and \", Mark(\"zero configuration\"), \".\"),\n",
    "        Blockquote(\n",
    "            P(\"Write semantic HTML in pure Python, get modern styling for free.\"),\n",
    "            Cite(\"MonsterUI Team\")),\n",
    "        footer=Small(\"Released February 2025\"),)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "python3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
